package com.vhans.db.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhans.core.domain.Example;
import com.vhans.core.utils.BeanCopyUtils;
import com.vhans.core.utils.StringUtils;
import com.vhans.db.mapper.ExampleMapper;
import com.vhans.db.model.dto.ConditionDTO;
import com.vhans.db.model.dto.example.ExampleDTO;
import com.vhans.db.model.vo.example.ExampleInfoVO;
import com.vhans.db.model.vo.example.ExampleVO;
import com.vhans.db.service.IExampleService;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 实例Service业务层处理
 *
 * @author vhans
 * @date 2023-05-20
 */
@Service
public class ExampleServiceImpl extends ServiceImpl<ExampleMapper, Example> implements IExampleService {
    @Autowired
    private ExampleMapper exampleMapper;

    /**
     * 查询实例列表
     *
     * @param condition 条件
     * @return 实例
     */
    @Override
    public List<ExampleVO> selectExampleVOList(ConditionDTO condition) {
        // 查询实例信息
        return exampleMapper.selectExampleVOList(condition);
    }

    /**
     * 新增实例
     *
     * @param example 实例
     * @return 插入id
     */
    @Override
    public Integer insertExample(ExampleDTO example) {
        // 要添加的实例
        Example newExample = BeanCopyUtils.copyBean(example, Example.class);
        Integer id = exampleMapper.selectOne(new LambdaQueryWrapper<Example>()
                .select(Example::getId)
                .eq(Example::getSpecification, newExample.getSpecification())
                .eq(Example::getCpu, newExample.getCpu())
                .eq(Example::getMemory, newExample.getMemory())).getId();
        if (StringUtils.isNotNull(id)) {
            // 存在相应规格和配置
            return id;
        } else {
            exampleMapper.insert(newExample);
            return newExample.getId();
        }
    }

    /**
     * 获取实例编辑信息
     *
     * @param id 实例主键
     * @return 实例
     */
    @Override
    public ExampleInfoVO selectExampleInfoById(Integer id) {
        // 查询实例信息
        ExampleInfoVO exampleInfoVO = exampleMapper.selectExampleInfoById(id);
        Assert.notNull(exampleInfoVO, "没有该实例");
        return exampleInfoVO;
    }

    /**
     * 修改实例
     *
     * @param example 实例
     */
    @Override
    public void updateExample(ExampleDTO example) {
        // 要修改的实例
        Example newExample = BeanCopyUtils.copyBean(example, Example.class);
        exampleMapper.updateById(newExample);
    }

    /**
     * 批量删除实例
     *
     * @param idList 需要删除的实例主键列表
     * @return 影响行
     */
    @Override
    public int deleteExampleByIdIdList(List<Integer> idList) {
        // 删除实例
        return exampleMapper.deleteBatchIds(idList);
    }
}
